package com.javafactroy.kunlong.bip.icp.message.test.base;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.Unpooled;
import lombok.Data;
import lombok.ToString;
import com.javafactroy.kunlong.bip.icp.message.dxp.iface.IMsgHeader;
import java.io.Serializable;
import java.util.UUID;

@Data
@ToString
public class TMsgHeader implements IMsgHeader, Serializable {

    public final static int LENGTH_FIELD_LENGTH = 4;
    public static int LENGTH_ADJUST_NETTY = -56;
    public static int msgHeaderLen = 68;
    public static int MSG_HEADER_LEN_OFFSET = 52;
    public static int MAGIC_NUMBER_LENGTH = 4;
    public final static int messageIdLength = 36;


    byte[] magicNumber = new byte[MAGIC_NUMBER_LENGTH];//{0x2b, 0x2b, 0x2b, 0x2b};
    int type; //0 req 1  res
    String messageId; //len 32
    int messageType;
    int versionId;
    int messageLen;
    int state;
    int reserve;
    int reserve1;
    public TMsgHeader() {
        type =TYPE_REQ;
        setMessageId(UUID.randomUUID().toString());
    }

    @Override
    public byte[] encode() {

        return encode2ByteBuf().array();
    }

    public ByteBuf encode2ByteBuf() {
        ByteBuf byteBuf = Unpooled.buffer(msgHeaderLen, msgHeaderLen);

        byteBuf.writeBytes(magicNumber);
        byteBuf.writeInt(type);
        byteBuf.writeBytes(messageId.getBytes());
        byteBuf.writeInt(messageType);
        byteBuf.writeInt(versionId);
        byteBuf.writeInt(messageLen);
        byteBuf.writeInt(state);
        byteBuf.writeInt(reserve);
        byteBuf.writeInt(reserve1);

        return byteBuf;
    }

    @Override
    public void decode(byte[] buf) {
        ByteBuf byteBuf = ByteBufAllocator.DEFAULT.buffer();
        byteBuf.writeBytes(buf);
        byteBuf.resetReaderIndex();
        decode(byteBuf);

    }

    void decodeMessageId(ByteBuf byteBuf) {
        byte[] bytes = new byte[messageIdLength];
        byteBuf.readBytes(bytes);
        setMessageId(new String(bytes));
    }

    public void decode(ByteBuf byteBuf) {

        byteBuf.readBytes(magicNumber);
        type = byteBuf.readInt();
        decodeMessageId(byteBuf);

        messageType = byteBuf.readInt();
        versionId = byteBuf.readInt();
        messageLen = byteBuf.readInt();
        state = byteBuf.readInt();
        reserve = byteBuf.readInt();
        reserve1 = byteBuf.readInt();

    }

    @Override
    public void check() {
        magicNumber.equals(magicNumber);
    }

    @Override
    public int getMsgId() {
        return 0;
    }


}
